package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.xutils.x;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.RequestParams;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.db.DataKeeper;
import artid.com.arttogoa.parser.ClassesPrser;
import artid.com.arttogoa.parser.OneStateParser;
import artid.com.arttogoa.parser.UserItem;
import artid.com.arttogoa.task.CallbackSky;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AlumAlert;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.CountDownTimer_Util;
import artid.com.arttogoa.util.GsonUtils;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.RegexUtil;
import artid.com.arttogoa.view.MyEditText;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsMessage;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称：RegisterActivity   
 * 类描述：注册   
 * 创建人：耿卫斌  
 * 创建时间：2016年5月16日 下午2:34:02      
 *
 */
public class RegisterActivity extends BaseActivity implements OnClickListener {
	private Button mNext, mGetCode;
	private MyEditText phone, code, password,nickname;
	private TextView classesTv;
	private CheckBox eyeBtn;
	private IntentFilter mIntentFilter;
	private String patternCoder = "(?<!\\d)\\d{6}(?!\\d)";
	private String strContent;
	private List<ClassesPrser> list_Classes;
	private String classesID;//艺术家类别ID
	private Handler mHandler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				code.setText(strContent);
				break;

			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		ArtWorkApp.getInstance().addActivity(this);
		initview();
	}

	private void initview() {
		mContext = this;
		mNext = (Button) findViewById(R.id.register_next);
		mTittle = (TextView) findViewById(R.id.title_text);
		mTittle.setText("注册");
		setBack();
		list_Classes=new ArrayList<ClassesPrser>();
		phone = (MyEditText) findViewById(R.id.register_phone);
		code = (MyEditText) findViewById(R.id.register_code);
		password = (MyEditText) findViewById(R.id.register_password);
		nickname = (MyEditText) findViewById(R.id.register_nickname);
		classesTv=(TextView) findViewById(R.id.register_classesTv);
		phone.addTextChangedListener(mTextChangedListener);
		code.addTextChangedListener(mTextChangedListener);
		password.addTextChangedListener(mTextChangedListener);
		nickname.addTextChangedListener(mTextChangedListener);
		classesTv.addTextChangedListener(mTextChangedListener);
		mGetCode = (Button) findViewById(R.id.register_get_code);
		eyeBtn = (CheckBox) findViewById(R.id.register_eye_btn);
		mNext.setOnClickListener(this);
		classesTv.setOnClickListener(this);
		mGetCode.setOnClickListener(this);
		eyeBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					// 如果选中，显示密码
					password.setTransformationMethod(HideReturnsTransformationMethod
							.getInstance());
				} else {
					// 否则隐藏密码
					password.setTransformationMethod(PasswordTransformationMethod
							.getInstance());
				}

			}
		});
		conditionJudge();
		//注册短信监听
		mIntentFilter = new IntentFilter();
		mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
		mIntentFilter.setPriority(Integer.MAX_VALUE);
		registerReceiver(broadcastReceiver, mIntentFilter);
		getClasses(false);
		registerUmPush();
	}

	/**
	 * 获取短信验证码
	 */
	private void getcode() {
		if (TextUtils.isEmpty(phone.getText().toString())) {
			Toast.makeText(mContext, "手机号不能为空~", 2).show();
			return;
		} else if (!RegexUtil.isMobile(phone.getText().toString())) {
			Toast.makeText(mContext, "手机号格式不正确，请重新输入~", 2).show();
			return;
		}
		VolleyBasic.getInstance(RegisterActivity.this)
		.post(Cache.sendregcode,
				VolleyMap.getInstance().sendregcode(
						phone.getText().toString()), OneStateParser.class,
						new VolleyCallback() {

			@Override
			public void onSuccess(VolleyData vd) {
				OneStateParser bean=(OneStateParser) vd.getData();
				if("1".equals(bean.getState())){
					//成功
					timer.start();
				}else if("0".equals(bean.getState())){
					//失败
					showToast("获取验证码失败，请重新点击获取");
					timer.cancel();		
					timer.onFinish();
				}else if("-1".equals(bean.getState())){
					//用户已注册
					AlertUtils.AlertTwoBtnDialog(mContext, "该用户已被注册", "去登陆", "忘记密码", Integer.parseInt(NetUtils.getDisplayMetrics(RegisterActivity.this).get(NetUtils.DM_WIDTH)), new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							switch (v.getId()) {
							case R.id.tv_ok:
								//去登陆
								AlertUtils.dismiss();
								finish();
								break;
							case R.id.tv_no:
								//忘记密码q
								AlertUtils.dismiss();
								Intent i=new Intent(mContext,ForgetPasswordActivity.class);
								startActivity(i);
								finish();
								break;
							default:
								break;
							}
						}
					});
				}

			}

			@Override
			public void onError(VolleyError volleyError) {

			}
		});
	}

	/**
	 * 条件判断
	 */
	private void conditionJudge(){
		if(!StringUtils.isEmpty(phone.getText().toString()) && !StringUtils.isEmpty(password.getText().toString()) && 
				!StringUtils.isEmpty(code.getText().toString()) && RegexUtil.isMobile(phone.getText().toString()) &&
				!StringUtils.isEmpty(nickname.getText().toString()) && !StringUtils.isEmpty(classesTv.getText().toString())){
			mNext.setEnabled(true);
			mNext.setBackgroundResource(R.drawable.red_frame);
		}else{
			mNext.setEnabled(false);
			mNext.setBackgroundResource(R.drawable.zjm_bg_dl);
		}
	}

	/**
	 * 对EditText监听
	 */
	TextWatcher mTextChangedListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   

			//对按钮的判断是否可用
			conditionJudge();
		}  
	};  


	/**
	 * 注册
	 */
	private void next() {
		VolleyBasic.showLoding(this);
		RequestParams params=new RequestParams(Cache.Registered);
		params.addHeader("Accept",  "application/json, text/javascript, */*");
		params.addParameter("mobile", phone.getText().toString());
		params.addParameter("code", code.getText().toString());
		params.addParameter("password", password.getText().toString());
		params.addParameter("client_type", "1");
		params.addParameter("realname", nickname.getText().toString());
		params.addParameter("aid", classesID);
		x.http().post(params, new CommonCallback<String>() {

			@Override
			public void onCancelled(CancelledException cex) {
				// TODO Auto-generated method stub
				System.out.println("主动停止网络请求");
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				// TODO Auto-generated method stub
				//请求错误
				if(isOnCallback==false){
					//ex异常信息不是来自回调方法
					System.out.println("ex异常信息不是来自回调方法："+ex.getMessage());
				}else{
					//ex异常信息是来自回调方法
					System.out.println("ex异常信息是来自回调方法："+ex.getMessage());
				}
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				System.out.println("请求完毕,不管成功失败");
			}

			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				//成功
				VolleyBasic.disMissLoding();
				Log.d("log", "Post请求结果："+result);
				String code=GsonUtils.message(result, "ret");
				String message=GsonUtils.message(result, "msg");
				if("1".equals(code)){
					MySharedPreferences.getMySharedPreferences(mContext).setValue("Phone", phone.getText().toString());
					MySharedPreferences.getMySharedPreferences(mContext).setValue("PassWord", password.getText().toString());
					login();
				}else if("0".equals(code)){
					showToast(message);
				}else if("-99".equals(code)){
					VolleyBasic.showRemoteLoginDialog(RegisterActivity.this);
				}
			}
		});
	}

	/**
	 * 获取艺术家类别
	 */
	private void getClasses(final Boolean isShowLoding){
		VolleyBasic.getInstance(RegisterActivity.this).post(isShowLoding,isShowLoding,
				Cache.selectArtistcategory,VolleyMap.getInstance().selectArtistcategory(), ClassesPrser.class,
				new VolleyCallback() {
			public void onSuccess(VolleyData vd) {
				list_Classes=(List<ClassesPrser>) vd.getList();
				if(list_Classes!=null && list_Classes.size()!=0){
					if(isShowLoding==true){
						AlumAlert.initAlertClassesDialog(RegisterActivity.this, list_Classes,  new CallbackSky() {

							@Override
							public void callBack(int index) {
								// TODO Auto-generated method stub
								classesID=list_Classes.get(index).getAid();
								showAffirmDialog(list_Classes.get(index).getAname());
							}
						});
					}
				}
			}
			public void onError(VolleyError volleyError) {

			}
		});
	}

	private void registerUmPush(){
		//当推送token获取不到的时候重新注册一下
		if(StringUtils.isEmpty(PushAgent.getInstance(this).getRegistrationId())){
			// 友盟注册
			//注册推送服务，每次调用register方法都会回调该接口
			PushAgent.getInstance(this).register(new IUmengRegisterCallback() {

				@Override
				public void onSuccess(String deviceToken) {
					//注册成功会返回device token
					Log.d("log", "友盟ID：" + deviceToken);
				}

				@Override
				public void onFailure(String s, String s1) {
					Log.d("log", "初始化友盟错误：" + s.toString() + "===" + s1.toString());
				}
			});
		}
	}


	/**
	 * 登录
	 */
	private void login() {
		VolleyBasic.getInstance(RegisterActivity.this).post(
				Cache.login,
				VolleyMap.getInstance().Login(phone.getText().toString(),
						password.getText().toString(),PushAgent.getInstance(this).getRegistrationId()), UserItem.class,
						new VolleyCallback() {
					public void onSuccess(VolleyData vd) {
						try {
							// TODO Auto-generated method stub
							System.out.println(vd.getJson());
							UserItem us = (UserItem) vd.getData();
							DataKeeper.keepSerializable(RegisterActivity.this, us);
							AppUtil.setUser();
							//暂时先把擅长保存到本地
							MySharedPreferences.getMySharedPreferences(mContext).setValue("Classes"+AppUtil.getUser().getUid(), classesTv.getText().toString());
							new Thread(new Runnable() {
								public void run() {
									try {
										// 调用sdk注册方法
										EMClient.getInstance().createAccount(AppUtil.getUser().getUid(), "yjbgp2016");
										runOnUiThread(new Runnable() {
											public void run() {
												//成功
											}
										});
									} catch (final HyphenateException e) {
										runOnUiThread(new Runnable() {
											public void run() {
												int errorCode=e.getErrorCode();
												if(errorCode==EMError.NETWORK_ERROR){
													Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
												}else if(errorCode == EMError.USER_ALREADY_EXIST){
													Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
												}else if(errorCode == EMError.USER_AUTHENTICATION_FAILED){
													Toast.makeText(getApplicationContext(), getResources().getString(R.string.Recording_without_permission), Toast.LENGTH_SHORT).show();
												}else if(errorCode == EMError.USER_ILLEGAL_ARGUMENT){
													Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
												}else{
													Toast.makeText(getApplicationContext(), getResources().getString(R.string.Login_failed) + e.getMessage(), Toast.LENGTH_SHORT).show();
												}
											}
										});
									}
								}
							}).start();
							Intent in = new Intent(RegisterActivity.this,UploadPhotoActivity.class);
							in.putExtra("isRegister", true);
							startActivity(in);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
					public void onError(VolleyError volleyError) {

					}
				});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.register_get_code:
			//获取验证码
			getcode();
			break;
		case R.id.register_classesTv:
			//选择类别
			if(list_Classes==null || list_Classes.size()==0){
				getClasses(true);
			}else{
				AlumAlert.initAlertClassesDialog(this, list_Classes,  new CallbackSky() {

					@Override
					public void callBack(int index) {
						// TODO Auto-generated method stub
						classesID=list_Classes.get(index).getAid();
						showAffirmDialog(list_Classes.get(index).getAname());
					}
				});
			}
			break;
		case R.id.register_next:
			//注册按钮
			next();
			break;
		default:
			break;
		}

	}

	private CountDownTimer_Util timer = new CountDownTimer_Util(60000, 1000) {

		@Override
		public void onTick(long millisUntilFinished) {
			mGetCode.setText((millisUntilFinished / 1000) + "秒后可重发");
			mGetCode.setClickable(false);
		}

		@Override
		public void onFinish() {
			mGetCode.setEnabled(true);
			mGetCode.setClickable(true);
			mGetCode.setText("获取验证码");
		}
	};

	/**
	 * 匹配短信中间的6个数字（验证码等）
	 * 
	 * @param patternContent
	 * @return
	 */
	private String patternCode(String patternContent) {
		if (TextUtils.isEmpty(patternContent)) {
			return null;
		}
		Pattern p = Pattern.compile(patternCoder);
		Matcher matcher = p.matcher(patternContent);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}
	/**
	 * 分类二次确认框
	 * @param position
	 */
	private void showAffirmDialog(final String classesName){
		AlertUtils.OneButtonAlertDialog(mContext, "选择分类后，将不可修改","知道了" ,Color.parseColor("#B5A478"),
				Integer.parseInt(NetUtils.getDisplayMetrics(this).get(NetUtils.DM_WIDTH)), new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.tv_ok:
					AlertUtils.dismiss();
					classesTv.setText(classesName);
					break;

				default:
					break;
				}
			}
		});

	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Object[] objs = (Object[]) intent.getExtras().get("pdus");
			for (Object obj : objs) {
				byte[] pdu = (byte[]) obj;
				SmsMessage sms = SmsMessage.createFromPdu(pdu);
				// 短信的内容
				String message = sms.getMessageBody();
				Log.d("log", "message     " + message);
				// 短息的手机号。。+86开头？
				String from = sms.getOriginatingAddress();
				Log.d("log", "from     " + from);
				if (!TextUtils.isEmpty(from)) {
					String code = patternCode(message);
					if (!TextUtils.isEmpty(code)) {
						strContent = code;
						mHandler.sendEmptyMessage(1);
					}
				}
			}
		}
	};

	protected void onDestroy() {
		super.onDestroy();
		//关闭广播
		unregisterReceiver(broadcastReceiver);
	};

}
